<div class="page-wrapper">
<div class="header">
    <a href="javascript:history.back();" class="left"><i class="icon-back"></i>菜单</a>
    <div id="order-preview-title" class="title">确认订单</div>
</div>

<div class="order-body">
    <div id="preview-food-list" class="food-list">

    </div>

    <div id="repeat-preview-food-item" class="food-item" style="display: none;">
        <div class="menu-name"><span class="name"></span></div>
        <span class="unitPrice"></span>
        <span class="preview-count"></span>
    </div>
    <div id="repeat-order-food-item" class="food-item" style="display: none;">
        <div class="menu-name"><span class="name"></span></div>
        <span class="unitPrice"></span>
        <span class="isDone"><span class="count"></span></span>
    </div>


    <div class="summary" style="display: none">
        <div class="pivot">
            <div class="pivot-left"></div>
            <div class="pivot-center"></div>
            <div class="pivot-right"></div>
        </div>
        <div class="summary-content">
            <div class="summary-line">
                <span class="summary-left">小计:</span>
                <span id="total" class="summary-right">￥400</span>
            </div>
            <div class="summary-line">
                <span class="summary-left">优惠:</span>
                <span id="coupon" class="summary-right">无</span>
            </div>
            <div class="total">总计：<span id="final-total" class="price">374.88</span></div>
            <div class="preview_button_wrapper">
                <button id="confirm" class="btn book">下单</button>
                <button id="checking" class="btn checking">审核中</button>
            </div>
            <!--<div class="pivot-bottom"></div>-->
            <div class="border-left"></div>
            <div class="border-right"></div>
        </div>

    </div>

</div>

<script>
    (function(){
        'use strict';
        console.log('preview');

        jsConfig();

        spa.addBeforeLeaveCallback(function(){
            if(timer){
                clearInterval(timer);
            }
        });

        var action = spa.getParam('action');
        if(action === 'order'){
            var orderId = spa.getParam('orderId');
            $.get('/wechatOrder/api/getParentOrderById/' + orderId, function (data) {
                console.log(data);
                if(data && data.order){
                    showOnlineOrder(data.order,data.menu);
                }
            });
        }else{
            if(cart.getCount() > 0){
                $('#order-preview-title').text('确认订单');
                showCartOrder(); //显示购物车数据
            }else{
                $.get('/api/getorder/user/' + window.userId,function(data){
                    showOnlineOrder(data); //显示未支付订单
                });
            }
        }

        $('#confirm').click(function(){
           if($(this).text() === '下单'){
                   if(!cart.tableId()){
                       postOrder(OrderState.cart_message);
                       /*if(confirm('未绑定台桌，请扫描台桌上的二维码')){
                           //扫码
                           scanQrc();
                       }*/
                   }else{
                       postOrder(OrderState.unconfirmed); //提交未审核订单
                   }
           }else{
               //微信支付结账
               callpay();
           }
        });

        var timer;
        function checkResult(subOrderId){
            timer = setInterval(function(){
                $.getJSON('/wechatOrder/api/qrySubOrderState/'+subOrderId,'',function(data){
                    console.log(data);
                    if(data){
                        if(data.state === OrderState.confirmed){
                            $('#checking').css({'background-image':'none',}).text('下单成功');
                            clearInterval(timer);
                            timer = undefined;
                        }else if(data.state === OrderState.refused){
                            $('#checking').css({'background-image':'none',}).text('下单失败');
                            clearInterval(timer);
                            timer = undefined;;
                        }
                    }
                });
            },15 * 1000);
        }


        /**
         * 提交购物车订单
         * @param state
         */
        function postOrder(state){
            if(cart.tableId()) {
                var $floatUI = common.showLoading('下单中,请稍后');
            }else{
                var $floatUI = common.showLoading('加载中,请稍后');
            }
            var order = cart.getOrder();
                order.state=state;

            console.log(order);
            console.log(window.userId + ' ' + window.storeId);
            $.post('/wechatOrder/api/order/',order,function(data){
                common.dismissLoading($floatUI);
                console.log(data);
                if(data && data.status == 'success'){
                    if(cart.tableId()) {
                        initCart();

                        common.toast('订单提交成功，请耐心等待审核...',4000);
//                        showOnlineOrder(data.order,data.menu);
                        $('#confirm').fadeOut();
                        $('#checking').fadeIn();

                        //获取审核结果
                        checkResult(data.orderId);
                    }else{
                        var cartOrderId=data.cartOrderId;
                        $.cookie("cartOrderId",cartOrderId,{expires:30,path:"/"});
                        if(confirm('请扫描您的餐桌上的二维码完成下单')){
                            //扫码
                            scanQrc();
                        }
                    }
                }else if(data && data.status == 'repeat'){
                    common.toast('此台桌还有未支付的订单');
                }else if(data && data.status == 'error'){
                    common.toast('订单数据异常');
                }
                else{
                    //提交订单失败
                    common.toast('订单提交失败，请确认网络正常...');
                }

            },'json');
        }


        function callpay()
        {
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            }else{
                jsApiCall();
            }
        }

        function getBindTable(){
            $.ajax({
                type:"GET",
                url:"/wechat/getBindTable?rank="+Math.random(),
                dataType:"json",
                timeout: 10000,
                success: function(data){
                    if(data!=null && data.tableId>0){
                        cart.tableId(data.tableId);
                        postOrder();
                    }

                },
                error:function(e){

                }
            });

        }

        function jsApiCall(){
            var loadInfo = common.showLoading("加载中，请稍后...");
            $.ajax({
                type:"GET",
                url:"/wechat/payOrder?rank="+Math.random(),
                dataType:"json",
                timeout: 10000,
                success: function(data){
                    common.dismissLoading(loadInfo);
                    if(data!=null){
                       WeixinJSBridge.invoke(
                               'getBrandWCPayRequest',
                               data,
                               function(res){
                                   if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                                        //window.location.href="http://nj.skypush.skysrt.com/wechat/index.html";
                                       wx.closeWindow();
                                   }else if(res.err_msg == "get_brand_wcpay_request:cancel"){

                                   }
                                   else{
                                       alert("支付订单失败");
                                   }

                               }
                       );
                   }else{
                       alert("支付数据异常。");
                   }
                },
                error:function(e){
                    common.dismissLoading(loadInfo.remove());
                    alert("支付数据异常。")
                }
            });
        }

        function scanQrc(){
            wx.ready(function () {
                wx.scanQRCode({
                    needResult: 0,
                    scanType: ["qrCode"],
                    success: function (res) {
                        //getBindTable();
                    }
                });
            });
        }

        function jsConfig(){

            //var currentUrl=window.location.href;
            var currentUrl="http://nj.skypush.skysrt.com/wechat/index.html";
            currentUrl=encodeURIComponent(currentUrl);
            $.ajax({
                type:"POST",
                url:"/wechat/jsConfig?rank="+Math.random(),
                data:"url="+currentUrl,
                dataType:"json",
                timeout: 10000,
                success: function(data){
                    if(data=="" || data == null){
                        return false;
                    }else{
                        wx.config({
                            debug: false,
                            appId: data.appId,
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            jsApiList: [
                                'closeWindow',
                                'scanQRCode'
                            ]
                        });
                    }
                },
                error:function(e){
                }
            });

        }

        function clearItem(){
            $('#preview-food-list').html('');
        }

        function showOnlineOrder(order,menus){
            clearItem();
            if(order.state == 1){
                $('#confirm').text('已结单').addClass('payed');
            }else{
                $('#confirm').text('结账');//.addClass('pay');
            }

            var $list = $('#preview-food-list');
            $.each(menus,function(index,item){
                var $item = cloneOrderItem();
                var unitPrice = item.foodDetail.unitPrice;
                var count = item.count;
                var price = unitPrice * count;
                $item.find('.menu-name .name').text(item.foodDetail.name);
                $item.find('.unitPrice').text('￥' + unitPrice);
                $item.find('.count').text('x'+count);
                $item.find('.price').text(price);
                if(item.removeFlag != 0){
                    $item.addClass('removed');
                    $item.find('.isDone').text('已退');
                }
                $list.append($item);
            });

            var originalPrice = common.fixOne(order.originalPrice);
            var price = common.fixOne(order.price);
            $('#total').text('￥'+ originalPrice);
            $('#coupon').text(originalPrice == price ? '无' : '￥' + (originalPrice - price).toFixed(1));
            $('#final-total').text('￥'+ price);

            $('.summary').show();
        }

        function showCartOrder(){
            $('#confirm').text('下单').removeClass('pay');
            showFoodList();
            setSummary();
        }

        function showFoodList(){
            var foods = cart.getOrder().foods;
            var $list = $('#preview-food-list');
            $(foods).each(function(key,food){
                var $item = clonePreviewItem();
                $item.find('.menu-name .name').text(food.name);
                $item.find('.unitPrice').text('￥' + food.price);
                $item.find('.preview-count').text(food.count);
                $item.find('.price').text('￥' + (food.price * food.count));
                $list.append($item);
            });

        }

        function setSummary() {
            var price = cart.getPrice();
            var oPrice = cart.originalPrice();
            $('#total').text('￥' + oPrice);
            if(oPrice > price){
                $('#coupon').text('￥'+(oPrice-price).toFixed(1));
            }else{
                $('#coupon').text('无');
            }
            $('#final-total').text('￥' + price);
            $('.summary').show();
        }

        var $repeatItem = undefined;
        function clonePreviewItem(){
            if(!$repeatItem){
                $repeatItem = $('#repeat-preview-food-item');
            }
            var $item = $repeatItem.clone();
            $item.attr('id','');
            $item.show();
            return $item;
        }

        var $repeatOrderItem = undefined;
        function cloneOrderItem() {
            if(!$repeatOrderItem){
                $repeatOrderItem = $('#repeat-order-food-item');
            }
            var $item = $repeatOrderItem.clone();
            $item.attr('id','');
            $item.show();
            return $item;
        }

    }());
</script>
</div>